package NewChatRoom;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

public class ServerGUI {
    private ChatServer chatServer;
    private JFrame jFrame;
    private JTextField ta_send;
    private JTextField ta_port;
    private JButton b_start;
    static JTable table_online;
    static JTextArea textArea;
    ResultToServer rs = new ResultToServer();

    public static void main(String[] args){
        ServerGUI UIprocess = new ServerGUI();
        UIprocess.createGUI();
    }
    public void createGUI(){
        jFrame = new JFrame("聊天室服务器管理");
        jFrame.setLocationRelativeTo(null);
        jFrame.setSize(600,600);
        jFrame.setLayout(new FlowLayout());

        JLabel la_port = new JLabel("服务器端口：");
        jFrame.add(la_port);
        ta_port = new JTextField(4);
        ta_port.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                int keyChar = e.getKeyChar();
                //屏蔽非法输入
                if(keyChar >= KeyEvent.VK_0 && keyChar <= KeyEvent.VK_9){

                }else {
                    e.consume();
                }
            }
        });
        jFrame.add(ta_port);
        b_start = new JButton("启动服务器");
        jFrame.add(b_start);
        b_start.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //启动
                startServer();
            }
        });
        JLabel la_msg = new JLabel("要发送的消息:");
        jFrame.add(la_msg);

        ta_send = new JTextField(30);
        ActionListener al_send = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMsgToAll();
            }
        };
        JButton b_send = new JButton("发送");
        b_send.addActionListener(al_send);
        jFrame.add(ta_send);
        jFrame.add(b_send);

        //显示在线用户的表格
        table_online = new JTable();
        List<serverHandlerThread> sht = ChatThreadManager.getAllServThread();
        UserInfoModel model = new UserInfoModel(sht);
        table_online.setModel(model);
        // 将表格放到滚动面板对象上
        JScrollPane scrollPane = new JScrollPane(table_online);
        // 设定表格在面板上的大小
        table_online.setPreferredScrollableViewportSize(new Dimension(400, 100));
        // 超出大小后，JScrollPane自动出现滚动条
        scrollPane.setAutoscrolls(true);
        jFrame.add(scrollPane);

        // 取得表格上的弹出菜单对象,加到表格上
        JPopupMenu pop = getTablePop();
        table_online.setComponentPopupMenu(pop);

        textArea = new JTextArea("返回的消息:\n");
        textArea.setEditable(false);
        JScrollPane returnTxt = new JScrollPane(textArea);
        returnTxt.setPreferredSize(new Dimension(400, 100));
        jFrame.add(returnTxt);

        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setVisible(true);

    }
    private JPopupMenu getTablePop(){
        JPopupMenu popm = new JPopupMenu();
        JMenuItem mi_send = new JMenuItem("发信");
        mi_send.setActionCommand("send");// 设定菜单命令关键字

        JMenuItem mi_del = new JMenuItem("踢掉");
        mi_del.setActionCommand("del");
        // 弹出菜单上的事件监听器对象
        ActionListener al = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String s = e.getActionCommand();
                // 哪个菜单项点击了，这个s就是其设定的ActionCommand
                popMenuAction(s);
            }
        };
        mi_send.addActionListener(al);
        mi_del.addActionListener(al);
        popm.add(mi_send);
        popm.add(mi_del);
        return popm;
    }
    //菜单项事件
    private void popMenuAction(String command){
        final int selectIndex = table_online.getSelectedRow();
        if(selectIndex==-1){
            JOptionPane.showMessageDialog(jFrame,"请选中一个用户");
            return;
        }
        if(command.equals("del")){
            ChatThreadManager.removeClient(selectIndex);
        }else if(command.equals("send")){
            UserInfo userInfo = ChatThreadManager.getUserInfo(selectIndex);
            //发送的对话框
            final JDialog dl = new JDialog(jFrame,true);
            dl.setLayout(new FlowLayout());
            dl.setLocationRelativeTo(null);
            dl.setTitle("对"+userInfo.getName()+"发送消息");
            dl.setSize(500,500);
            final JTextField tf = new JTextField(20);
            JButton jb = new JButton("发送");
            dl.add(tf);
            dl.add(jb);

            jb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    //System.out.println("发送了一条消息啊...");
                    rs.print("对"+userInfo.getName()+"悄悄的说:"+tf.getText()+"\n");
                    String msg = "系统悄悄对你说:" + tf.getText();
                    ChatThreadManager.sendMsgToOne(selectIndex,msg);
                    tf.setText("");

                    dl.dispose();
                }
            });
            dl.setVisible(true);
        }else {
            JOptionPane.showMessageDialog(jFrame, "未知菜单:" + command);
        }
        //刷新表格
        SwingUtilities.updateComponentTreeUI(table_online);
    }

    private void sendMsgToAll(){
        String msg = ta_send.getText();
        ChatThreadManager.castMsg(msg);
        ta_send.setText("");
    }

    //服务器启动事件
    private void startServer(){
        if(chatServer == null){
            String s_port = ta_port.getText();
            int port = Integer.parseInt(s_port);
            chatServer = new ChatServer(port);
            //用独立线程进行运行，GUI不会卡顿
            chatServer.start();
            jFrame.setTitle("聊天室服务器管理:正在运行中");
            b_start.setText("停止服务器");
        }else if(chatServer.isRunning()){//不是null，说明在运行
            chatServer.stopChatServer();//停止
            chatServer=null;
            // 清除所有己在运行的客户端处理线程
            ChatThreadManager.removeAllClient();
            rs.print("服务器停止\n");
            jFrame.setTitle("聊天室服务器管理:已停止");
            b_start.setText("启动服务器");
        }
    }
}
